let leftArrow = document.querySelector(".leftArrow");
let rightArrow = document.querySelector(".rightArrow");
let pointList = document.querySelectorAll(".pointBox li");
let ul = document.querySelector(".carouselBox ul");
let carouselBox = document.querySelector(".carouselBox");
let nowIndex = 0;
let timer;
let isRun = true;

/**
 * 左箭头事件
 */
leftArrow.addEventListener("click", function() {
	if (isRun) {
		isRun = false;
		if (++nowIndex == ul.childElementCount) {
			leftEndRun();
		} else {
			run();
		}
	}
})

/**
 * 左边尽头函数 -> 最后一张去到第一张
 */
function leftEndRun() {

	ul.appendChild(ul.firstElementChild.cloneNode(true));

	ul.style.transform = `translateY(-${nowIndex}00%)`;

	ul.addEventListener("transitionend", function() {
		ul.style.transition = "none";
		ul.style.transform = `translateY(0%)`;

		// 读取 ul 的 transition 属性 提醒代码运行时注意样式改变的能力
		getComputedStyle(ul).transition;
		ul.style.transition = "";

		ul.removeChild(ul.lastElementChild);
		nowIndex = 0;
		pointActive();
	}, {
		once: true
	})
}

/**
 * 右边点击事件
 */
rightArrow.addEventListener("click", function() {
	if (isRun) {
		isRun = false;
		if (--nowIndex < 0) {
			rightEndRun();
		} else {
			run();
		}
	}
})

/**
 * 右边尽头事件
 */
function rightEndRun() {
	ul.insertBefore(ul.lastElementChild.cloneNode(true), ul.firstElementChild);
	ul.style.transition = "none";
	ul.style.transform = `translateY(-100%)`;

	getComputedStyle(ul).transition;
	ul.style.transition = "";
	ul.style.transform = `translateY(0%)`;

	ul.addEventListener("transitionend", function() {
		ul.style.transition = "none";
		nowIndex = ul.childElementCount - 2;
		ul.style.transform = `translateY(-${nowIndex}00%)`;
		ul.removeChild(ul.firstElementChild);

		getComputedStyle(ul).transition;
		ul.style.transition = "";

		pointActive();
	}, {
		once: true
	})
}

/**
 * 主函数
 */
function run() {
	ul.style.transform = `translateY(-${nowIndex}00%)`;
	pointActive();
}

/**
 * 小圆点激活类的切换
 */
function pointActive() {
	pointList.forEach(function(item) {
		item.classList.remove("active");
	})
	pointList[nowIndex].classList.add("active");
	isRun = true;
}

/**
 * 小圆点的点击事件
 * @param {Object} item
 * @param {Object} index
 */
pointList.forEach(function(item, index) {
	item.addEventListener("click", function() {
		nowIndex = index;
		run();
	})
})

/**
 * 定时器
 */
timer = setInterval(function() {
	if (++nowIndex == ul.childElementCount) {
		leftEndRun();
	} else {
		run();
	}
}, 2000)

/**
 * 鼠标移入
 */
carouselBox.addEventListener("mouseenter", function() {
	clearInterval(timer);
})

/**
 * 鼠标移出
 */
carouselBox.addEventListener("mouseleave", function() {
	timer = setInterval(function() {
		if (++nowIndex == ul.childElementCount) {
			leftEndRun();
		} else {
			run();
		}
	}, 2000)
})
